<script>
import { ref, onMounted, reactive } from 'vue';
import { searchBusinessByBusinessName, listBusinessByType, ListBusiness } from '@/api/index';
import { useRouter } from 'vue-router'
export default {
  setup() {
    const active = ref(0);
    const router = useRouter();
    /*   const displayedbusiness = ref([]) */
    const searchvalue = ref('')
    const originlist = ref([])
    const currentBaseURL = window.location.origin + window.location.pathname.split('/').slice(0, -1).join('/');
    const state = reactive({
      displayedbusiness: []
    });
    const loading = ref(false);
    const finished = ref(false);
    const curPage = ref(1);
    const typetagslist = ref([
      { text: '全部', value: 0 },
      { text: '鲁菜', value: 1 },
      { text: '川菜', value: 2 },
      { text: '粤菜', value: 3 },
      { text: '苏菜', value: 4 },
      { text: '浙菜', value: 5 },
      { text: '闽菜', value: 6 },
      { text: '湘菜', value: 7 },
    ]);
    const initData = async (pageNum) => {
      try {
        const response = await ListBusiness({ pageNum: pageNum, pageSize: 10 });
        for (let i = 0; i < response.data.records.length; i++) {
          state.displayedbusiness.push(response.data.records[i]);
        }

        if (state.displayedbusiness.length >= response.data.total) {
          finished.value = true;
        }
        /* displayedbusiness.value = response.data.records; */
        originlist.value = [...state.displayedbusiness];
        console.log(originlist.value)
      } catch (error) {
        console.error('获取商家列表数据时出错:', error);
      }
    };

    onMounted(() => {
      initData(curPage.value, 10);
      initData(curPage.value, 10);
    });
    const getBusinessByType = async ({ name, pageNum }) => {
      try {
        curPage.value = 1;
        finished.value = false;
        state.displayedbusiness.splice(0, state.displayedbusiness.length)
        searchvalue.value = '';
        if (name === 0) {
          const response = await ListBusiness({ pageNum: pageNum, pageSize: 10 });
          for (let i = 0; i < response.data.records.length; i++) {
            state.displayedbusiness.push(response.data.records[i]);
          }

          if (state.displayedbusiness.length >= response.data.total) {
            finished.value = true;
          }

          return
        }
        const response = await listBusinessByType({
          businessType: name,
          pageNum: pageNum,
          pageSize: 10
        });
        console.log('这是response', response)
        for (let i = 0; i < response.data.records.length; i++) {
          state.displayedbusiness.push(response.data.records[i]);
        }

        if (state.displayedbusiness.length >= response.data.total) {
          finished.value = true;
        }
      } catch (error) {
        console.error('获取商家列表数据时出错:', error);
      }
    };

    const loadBusinessByType = async ({ name, pageNum }) => {
      try {
        console.log(pageNum)
        if (name === 0) {
          const response = await ListBusiness({ pageNum: pageNum, pageSize: 10 });
          for (let i = 0; i < response.data.records.length; i++) {
            state.displayedbusiness.push(response.data.records[i]);
          }

          if (state.displayedbusiness.length >= response.data.total) {
            finished.value = true;
          }
          return
        }
        const response = await listBusinessByType({
          businessType: name,
          pageNum: pageNum,
          pageSize: 10
        });

        for (let i = 0; i < response.data.records.length; i++) {
          state.displayedbusiness.push(response.data.records[i]);
        }

        if (state.displayedbusiness.length >= response.data.total) {
          finished.value = true;
        }
        console.log(response.data)
        console.log(state.displayedbusiness.length)
        console.log(finished.value)
      } catch (error) {
        console.error('获取商家列表数据时出错:', error);
      }
    };


    const searchBusiness = async (val, pageNum) => {
      try {
        curPage.value = 1;
        finished.value = false;
        state.displayedbusiness.splice(0, state.displayedbusiness.length)
        active.value = 0;
        const response = await searchBusinessByBusinessName({
          businessName: val,
          pageNum: pageNum,
          pageSize: 10
        });
        for (let i = 0; i < response.data.records.length; i++) {
          state.displayedbusiness.push(response.data.records[i]);
        }

        if (state.displayedbusiness.length >= response.data.total) {
          finished.value = true;
        }
        console.log(response.data)
        console.log(state.displayedbusiness.length)
        console.log(finished.value)
      } catch (error) {
        console.error('获取商家列表数据时出错:', error);
      }
    };

    const loadSearchBusiness = async (val, pageNum) => {
      try {
        const response = await searchBusinessByBusinessName({
          businessName: val,
          pageNum: pageNum,
          pageSize: 10
        });
        for (let i = 0; i < response.data.records.length; i++) {
          state.displayedbusiness.push(response.data.records[i]);
        }

        if (state.displayedbusiness.length >= response.data.total) {
          finished.value = true;
        }
      } catch (error) {
        console.error('获取商家列表数据时出错:', error);
      }
    };

    const Oncancel = async () => {
      initData(curPage.value, 10)
    }

    const onLoad = async () => {
      loading.value = true;
      console.log('加载中。。。。。。。。。。。。。。')
      curPage.value += 1;
      if (searchvalue.value.trim() !== '') { // 如果有搜索关键词，则执行搜索加载
        console.log('掉的是这个')
        await loadSearchBusiness(searchvalue.value, curPage.value);
      } else if (active.value !== '') { // 假设当active不是0时，表示用户选择了分类标签
        console.log('没搜索')
        await loadBusinessByType({ name: active.value, pageNum: curPage.value });

      }

      setTimeout(() => {
        loading.value = false;
      }, 1000);
      
    };


    const toBusiness = (businessId) => {
      router.push({ path: `/orderdishes/${businessId}` })
    }


    return {
      typetagslist,
      active,
      /*     displayedbusiness, */
      ListBusiness,
      listBusinessByType,
      searchBusinessByBusinessName,
      initData,
      getBusinessByType,
      searchBusiness,
      searchvalue,
      Oncancel,
      originlist,
      currentBaseURL,
      onLoad,
      finished,
      state,
      loading,
      curPage,
      toBusiness
    };
  },
};
</script>

<template>
  <div>
    <div class="home">
      <div class="header">
        <!--       <van-dropdown-menu class="adress-select" style="color: pink;">
        <van-dropdown-item v-model="value1" :options="option1" />
      </van-dropdown-menu> -->
        <van-search v-model="searchvalue" shape="round" background="#5ca5ee" placeholder="请输入搜索关键词"
          class="search-place" @search="searchBusiness" @cancel="Oncancel" show-action />
      </div>
      <van-list v-model:loading="loading" :finished="finished" :immediate-check="false" finished-text="没有更多了"
        @load="onLoad" :offset="200">
        <div class="main">
          <van-tabs v-model:active="active" @click-tab="getBusinessByType">
            <van-tab v-for="typetag in typetagslist" :title="typetag.text" :name="typetag.value" :key="typetag.value" />
          </van-tabs>
          <van-cell-group style="padding-bottom: 5px;background-color: #f6f6f6;">
            <van-card style="padding-bottom: 5px; background-color: white;color: #1989fa;font-size: 15px;" v-for="business in state.displayedbusiness"
              :key="business.businessId" :desc="business.businessExplain" :title="business.businessName"
              :thumb="business.businessImg" @click="toBusiness(business.businessId)">
              <template #bottom>
                <div style="margin: 5px;">
                  <label style="color: black;">起送费:￥{{ business.starPrice }}</label>
                  <label style="margin-left: 12px;color: black;">配送费:￥{{ business.deliveryPrice }}</label>
                </div>
              </template>
            </van-card>

          </van-cell-group>
        </div>
      </van-list>
    </div>
    <van-tabbar fixed route>
      <van-tabbar-item replace to="/" icon="home-o">首页</van-tabbar-item>
      <van-tabbar-item replace to="/order" icon="shopping-cart-o">订单</van-tabbar-item>
      <van-tabbar-item replace to="/user" icon="user-o">我的</van-tabbar-item>
    </van-tabbar>
  </div>

</template>

<style lang="scss" scoped>
.header {
  display: flex;
  align-items: center;
  /* 垂直居中 */
  width: 100%;
  height: 50px;
}

.home {
  width: 100%;
  height: 100%;

}


.search-place {
  width: 100%;
  background-color: #5ca5ee;
}

.footer {
  margin: 500px;
}
</style>
